<template>
  <VCard width="600px" class="mx-auto mt-10">
    <VToolbar color="primary" dark>
      <VToolbarTitle>初访预约管理系统</VToolbarTitle>
    </VToolbar>
    <VCardText>
      <!-- 查询区域 -->
      <div class="d-flex align-center mb-6">
        <VTextField
          v-model="studentId"
          label="请输入你的学号"
          variant="outlined"
          color="primary"
          class="mr-4"
          style="flex: 1;"
          :rules="[rules.required]"
        />
        <VBtn 
          color="primary" 
          @click="searchAppointment"
          :loading="loading"
          :disabled="!studentId"
        >
          查询
        </VBtn>
      </div>

      <!-- 预约信息显示区域 -->
      <div v-if="appointmentInfo" class="appointment-info">
        <VCard variant="outlined" class="pa-4">
          <VCardTitle class="text-h6 mb-4">预约信息</VCardTitle>
          <div v-if="userInfo" class="info-item">
            <span class="label">姓名：</span>
            <span class="value">{{ userInfo.name || '未设置' }}</span>
          </div>
          <div v-if="userInfo && userInfo.extra_info" class="info-item">
            <span class="label">院系：</span>
            <span class="value">{{ parseDepartment(userInfo.extra_info) }}</span>
          </div>
          <div class="info-item">
            <span class="label">学号：</span>
            <span class="value">{{ userInfo?.username || '未设置' }}</span>
          </div>
          <div class="info-item">
            <span class="label">预约时间：</span>
            <span class="value">{{ formatDateTime(appointmentInfo.scheduled_time) }}</span>
          </div>
          <div class="info-item">
            <span class="label">预约地点：</span>
            <span class="value">{{ appointmentInfo.scheduled_place }}</span>
          </div>
          <div class="info-item">
            <span class="label">预约状态：</span>
            <VChip 
              :color="getStatusColor(appointmentInfo.status)" 
              size="small"
              class="ml-2"
            >
              {{ getStatusText(appointmentInfo.status) }}
            </VChip>
          </div>
          <!-- 操作按钮 -->
          <div class="mt-4 text-center">
            <VBtn 
              color="error" 
              variant="outlined"
              @click="showCancelDialog = true"
              v-if="appointmentInfo.status !== 'CANCELED' && appointmentInfo.status !== 'COMPLETED'"
              class="mr-2"
            >
              取消预约
            </VBtn>
            <VBtn 
              color="primary" 
              variant="outlined"
              @click="showAllRecordsDialog"
              :loading="allLoading"
            >
              全部记录
            </VBtn>
          </div>
        </VCard>
      </div>

      <!-- 无预约信息提示 -->
      <div v-else-if="searched && !appointmentInfo" class="no-appointment">
        <VCard variant="outlined" class="pa-4 text-center">
          <VIcon size="64" color="grey" class="mb-4">mdi-calendar-remove</VIcon>
          <div class="text-h6 mb-2">暂无预约信息</div>
          <div class="text-body-2 text-grey">该学号没有找到预约记录</div>
        </VCard>
      </div>
    </VCardText>
  </VCard>

  <!-- 无预约弹窗 -->
  <VDialog v-model="showNoAppointmentDialog" max-width="400px" persistent @click:outside="closeNoAppointmentDialog">
    <VCard>
      <VCardTitle class="text-h6 text-center pa-4">
        <VIcon size="48" color="warning" class="mb-2">mdi-alert-circle</VIcon>
        <div>用户没有预约</div>
      </VCardTitle>
      <VCardText class="text-center">
        该学号没有找到预约记录，请确认学号是否正确。
      </VCardText>
      <VCardActions class="justify-center pa-4">
        <VBtn color="secondary" @click="closeNoAppointmentDialog">确定</VBtn>
      </VCardActions>
    </VCard>
  </VDialog>

  <!-- 取消预约弹窗 -->
  <VDialog v-model="showCancelDialog" max-width="500px" persistent @click:outside="closeCancelDialog">
    <VCard>
      <VToolbar color="error" dark>
        <VToolbarTitle>取消预约</VToolbarTitle>
        <VSpacer />
        <VBtn icon @click="closeCancelDialog">
          <VIcon>mdi-close</VIcon>
        </VBtn>
      </VToolbar>
      <VCardText class="pa-4">
        <div class="mb-4">
          <p class="text-body-1 mb-2">请填写取消预约的原因：</p>
          <VTextarea
            v-model="cancelReason"
            label="取消原因"
            variant="outlined"
            rows="4"
            :rules="[rules.required]"
            placeholder="请输入取消预约的具体原因..."
          />
        </div>
        <VAlert type="warning" class="mb-4">
          <template v-slot:prepend>
            <VIcon>mdi-alert</VIcon>
          </template>
          <div class="text-body-2">
            <strong>重要提醒：</strong>距离预约时间不足24小时将无法取消预约。
          </div>
        </VAlert>
      </VCardText>
      <VDivider />
      <VCardActions class="pa-4">
        <VSpacer />
        <VBtn color="secondary" @click="closeCancelDialog">取消</VBtn>
        <VBtn 
          color="error" 
          @click="confirmCancelAppointment"
          :loading="cancelLoading"
          :disabled="!cancelReason.trim()"
        >
          确认取消
        </VBtn>
      </VCardActions>
    </VCard>
  </VDialog>

  <!-- 时间不足弹窗 -->
  <VDialog v-model="showTimeLimitDialog" max-width="400px" persistent @click:outside="closeTimeLimitDialog">
    <VCard>
      <VCardTitle class="text-h6 text-center pa-4">
        <VIcon size="48" color="error" class="mb-2">mdi-clock-alert</VIcon>
        <div>无法取消预约</div>
      </VCardTitle>
      <VCardText class="text-center">
        距离预约时间小于24小时，无法取消预约。
      </VCardText>
      <VCardActions class="justify-center pa-4">
        <VBtn color="primary" @click="closeTimeLimitDialog">确定</VBtn>
      </VCardActions>
    </VCard>
  </VDialog>

  <!-- 全部记录弹窗 -->
  <VDialog v-model="showAllRecords" max-width="900px" persistent @click:outside="closeAllRecordsDialog">
    <VCard>
      <VToolbar color="primary" dark>
        <VToolbarTitle>全部预约记录</VToolbarTitle>
        <VSpacer />
        <VBtn icon @click="closeAllRecordsDialog">
          <VIcon>mdi-close</VIcon>
        </VBtn>
      </VToolbar>
      <VCardText class="pa-4">
        <VTable dense>
          <thead>
            <tr>
              <th>申请时间</th>
              <th>预约时间</th>
              <th>预约状态</th>
              <th>取消原因</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in allAppointments" :key="item.id">
              <td>{{ formatDateTime(item.apply_time) }}</td>
              <td>{{ formatDateTime(item.scheduled_time) }}</td>
              <td>
                <VChip :color="getStatusColor(item.status)" size="small">
                  {{ getStatusText(item.status) }}
                </VChip>
              </td>
              <td>{{ item.cancel_reason || '' }}</td>
            </tr>
          </tbody>
        </VTable>
        <div v-if="allLoading" class="text-center mt-2">加载中...</div>
        <div v-if="!allLoading && allAppointments.length === 0" class="text-center mt-4 text-grey">
          暂无预约记录
        </div>
        <div class="text-center mt-6">
          <VBtn color="primary" @click="closeAllRecordsDialog">返回</VBtn>
        </div>
      </VCardText>
    </VCard>
  </VDialog>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useSnackbarStore } from '@/store/snackbarStore';
import { useNotificationStore } from '@/store/notificationStore';
import { searchAppointmentByStudentId, cancelAppointment, getHistoryAppointmentsByStudentId, getAllAppointmentsByStudentId } from '@/api/appointment';

const router = useRouter();
const snackbarStore = useSnackbarStore();
const notificationStore = useNotificationStore();

const studentId = ref('');
const appointmentInfo = ref(null);
const userInfo = ref(null);
const loading = ref(false);
const searched = ref(false);
const showNoAppointmentDialog = ref(false);
const showCancelDialog = ref(false);
const showTimeLimitDialog = ref(false);
const cancelReason = ref('');
const cancelLoading = ref(false);
const historyAppointments = ref([]);
const historyLoading = ref(false);
const allAppointments = ref([]);
const allLoading = ref(false);
const showAllRecords = ref(false);

const rules = {
  required: (v: string) => !!v || '请输入学号'
};

// 查询预约信息
const searchAppointment = async () => {
  if (!studentId.value) {
    snackbarStore.showMessage('请输入学号');
    return;
  }

  loading.value = true;
  searched.value = false;
  appointmentInfo.value = null;
  userInfo.value = null;
  historyAppointments.value = [];

  try {
    const { data: res } = await searchAppointmentByStudentId(studentId.value);
    
    if (res.success) {
      if (res.data) {
        // 找到预约信息
        appointmentInfo.value = res.data.appointment;
        userInfo.value = res.data.user;
        searched.value = true;
        // 查询历史预约
        historyLoading.value = true;
        try {
          const { data: historyRes } = await getHistoryAppointmentsByStudentId(studentId.value);
          if (historyRes.success) {
            historyAppointments.value = historyRes.data || [];
          } else {
            snackbarStore.showMessage(historyRes.message || '历史记录查询失败');
          }
        } catch (e) {
          snackbarStore.showMessage('历史记录查询失败');
        } finally {
          historyLoading.value = false;
        }
      } else {
        // 没有找到预约信息
        searched.value = true;
        showNoAppointmentDialog.value = true;
      }
    } else {
      // 查询失败
      snackbarStore.showMessage(res.message || '查询失败');
    }
  } catch (error) {
    console.error('查询预约失败:', error);
    snackbarStore.showMessage('查询失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '未设置';
  const date = new Date(dateTimeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  });
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const statusColors = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'error',
    'COMPLETED': 'info',
    'CANCELED': 'grey'
  };
  return statusColors[status] || 'grey';
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusTexts = {
    'PENDING': '待审核',
    'APPROVED': '已批准',
    'REJECTED': '已拒绝',
    'COMPLETED': '已完成',
    'CANCELED': '已取消'
  };
  return statusTexts[status] || status;
};

// 解析院系
const parseDepartment = (extraInfo) => {
  try {
    const obj = typeof extraInfo === 'string' ? JSON.parse(extraInfo) : extraInfo;
    return obj.department || '未设置';
  } catch {
    return '未设置';
  }
};

// 关闭无预约弹窗
const closeNoAppointmentDialog = () => {
  showNoAppointmentDialog.value = false;
  // 清空输入框，让用户可以重新输入
  studentId.value = '';
  appointmentInfo.value = null;
  searched.value = false;
};

// 关闭取消预约弹窗
const closeCancelDialog = () => {
  showCancelDialog.value = false;
  cancelReason.value = '';
};

// 关闭时间限制弹窗
const closeTimeLimitDialog = () => {
  showTimeLimitDialog.value = false;
  closeCancelDialog();
};

// 显示全部记录弹窗
const showAllRecordsDialog = async () => {
  if (!studentId.value) {
    snackbarStore.showMessage('请先查询学号');
    return;
  }

  allLoading.value = true;
  showAllRecords.value = true;

  try {
    const { data: res } = await getAllAppointmentsByStudentId(studentId.value);
    if (res.success) {
      allAppointments.value = res.data || [];
    } else {
      snackbarStore.showMessage(res.message || '查询全部记录失败');
    }
  } catch (error) {
    console.error('查询全部记录失败:', error);
    snackbarStore.showMessage('查询全部记录失败，请重试');
  } finally {
    allLoading.value = false;
  }
};

// 关闭全部记录弹窗
const closeAllRecordsDialog = () => {
  showAllRecords.value = false;
  allAppointments.value = [];
};

// 确认取消预约
const confirmCancelAppointment = async () => {
  if (!cancelReason.value.trim()) {
    snackbarStore.showMessage('请输入取消原因');
    return;
  }

  cancelLoading.value = true;
  try {
    const { data: res } = await cancelAppointment({
      appointmentId: appointmentInfo.value.id,
      cancelReason: cancelReason.value
    });

    if (res.success) {
      snackbarStore.showMessage('预约已成功取消');
      // 添加通知
      notificationStore.addAppointmentNotification(
        `学号 ${studentId.value} 的预约已成功取消`,
        '/appointment-management',
        appointmentInfo.value.id.toString()
      );
      // 更新本地状态
      appointmentInfo.value.status = 'CANCELED';
      appointmentInfo.value.cancel_reason = cancelReason.value;
      closeCancelDialog();
    } else {
      if (res.message && res.message.includes('24小时')) {
        // 时间不足的情况
        showTimeLimitDialog.value = true;
      } else {
        snackbarStore.showMessage(res.message || '取消预约失败');
      }
    }
  } catch (error) {
    console.error('取消预约失败:', error);
    snackbarStore.showMessage('取消预约失败，请重试');
  } finally {
    cancelLoading.value = false;
  }
};
</script>

<style scoped>
.appointment-info {
  margin-top: 20px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.label {
  font-weight: 600;
  color: #333;
  min-width: 100px;
}

.value {
  color: #666;
  flex: 1;
}

.no-appointment {
  margin-top: 20px;
}
</style> 